var createError = require('http-errors');
var express = require('express');
var path = require('path');
// cookie
var cookieParser = require('cookie-parser');
// session 记得安装，这个不是node的官方模块
let session = require('express-session')
// 日志的输出
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var sessionRouter = require('./routes/mySession')
let uploadRouter = require('./routes/uploadRouter')
let download = require('./routes/download')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// express 的中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//cookie 中间件
app.use(cookieParser('secret'));
// session 中间件
// session 配置
app.use(session({
  // 加盐
  secret: "asyAdmin",
  // 强制保存Session
  resave: true,
  // 是否保存初始化session
  saveUninitialized: true,
  // 相当于加密得cookie
  cookie: {
    //设置session的有效期为一周
    maxAge: 7 * 24 * 60 * 60 * 1000
  }
}))

// 到public里面找文件，如果没有走下面路由
app.use(express.static(path.join(__dirname, 'public')));


// 路由匹配
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/mySession', sessionRouter)
app.use("/imgUpload", uploadRouter)
app.use('/download',download)
// catch 404 and forward to error handler 404报错
app.use(function (req, res, next) {
  res.render('404.ejs')
  next()
});

// error handler 处理错误的中间件
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


module.exports = app;
